/****************************************
 * 2018 - 2021 版权所有 CopyRight(c) 快程乐码信息科技有限公司所有, 未经授权，不得复制、转发
 */

package com.kclm.security03.config.security.dto;

import com.kclm.security03.modules.system.entity.Role;
import com.kclm.security03.modules.system.entity.User;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/******************
 * @Author yejf
 * @Version v1.0
 * @Create 2020-07-26 22:51
 * @Description Spring Security自带的那个User的信息太少，所以封装了一个 SecurityUser
 */
@Slf4j
@Data
public class SecurityUser implements UserDetails {

    /** 当前登录用户 */
    private transient User currentUserInfo;

    /** 角色 */
    private transient List<Role> roleList;

    public SecurityUser() {

    }

    public SecurityUser(User user) {
        if(user != null) {
            this.currentUserInfo = user;
        }
    }

    public SecurityUser(User user, List<Role> roleList) {
        log.debug("构造SecurityUser 实例，传入user 和 roleList");
        if(user != null) {
            this.currentUserInfo = user;
            this.roleList = roleList;
        }
    }

    /****************
     * 获取用户的角色信息
     * @return
     */
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        log.debug("获取当前登录用户的角色信息");
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        //判断传进来的集合 List<Role> 是否为NULL
        if(!CollectionUtils.isEmpty(this.roleList)) {
            for(Role role : this.roleList) {
                authorities.add(new SimpleGrantedAuthority(role.getCode()));
            }
        }
        log.debug("当前认证用户的角色有："+authorities.size() +" 个");
        //返回
        return authorities;
    }

    @Override
    public String getPassword() {
        return this.currentUserInfo.getPassword();
    }

    @Override
    public String getUsername() {
        return this.currentUserInfo.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        log.debug("SecurityUser isAccountNotExpired: true");
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        log.debug("SecurityUser isAccountNonLocked: true");
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        log.debug("SecurityUser isCredentialsNonExpired: true");
        return true;
    }

    @Override
    public boolean isEnabled() {
        log.debug("SecurityUser isEnable: true");
        return true;
    }



}
